package com.argrace.smart.fragment;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextPaint;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.sdk.android.openaccount.OpenAccountSDK;
import com.alibaba.sdk.android.openaccount.ui.OpenAccountUIService;
import com.aliyun.alink.business.alink.ALinkBusinessEx;
import com.aliyun.alink.business.helper.ChannelBindHelper;
import com.aliyun.alink.business.login.AlinkLoginBusiness;
import com.aliyun.alink.business.login.IAlinkLoginCallback;
import com.aliyun.alink.sdk.net.anet.api.AError;
import com.aliyun.alink.sdk.net.anet.api.transitorynet.TransitoryRequest;
import com.aliyun.alink.sdk.net.anet.api.transitorynet.TransitoryResponse;
import com.argrace.smart.ArgraceApplication;
import com.argrace.smart.R;
import com.argrace.smart.activity.SubDeviceListActivity;
import com.argrace.smart.adapter.MyWangGuanAdapter;
import com.argrace.smart.base.BaseFragment;
import com.argrace.smart.entity.WangGuanDeviceEntity;
import com.argrace.smart.envconfig.EnvConfigure;
import com.argrace.smart.ui.ArgraceDialog;
import com.argrace.smart.ui.EmptyRecycleView;
import com.argrace.smart.util.AlinkHttpUtil;
import com.argrace.smart.util.Logg;
import com.bigkoo.svprogresshud.SVProgressHUD;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by argrace_dev_1 on 2018/2/7.
 */

public class WangGuanFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener {
    EmptyRecycleView recyclerView;
    SwipeRefreshLayout refreshLayout;
    DrawerLayout mDrawerLayout;
    //    LinearLayout left_ll;
//    TextView userid, loginout;
    private MyWangGuanAdapter adapter;
    private ArrayList<WangGuanDeviceEntity> lists = new ArrayList<>();
    private Handler handler = new Handler();
    private boolean isFoundDevice = false;
    private SVProgressHUD mSVProgressHUD;
    OpenAccountUIService openAccountService = OpenAccountSDK.getService(OpenAccountUIService.class);

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_wangguan, container, false);
    }

    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        init();
        super.onActivityCreated(savedInstanceState);
    }

    private void setView() {
        recyclerView = (EmptyRecycleView) getView().findViewById(R.id.recyclerView);
        refreshLayout = (SwipeRefreshLayout) getView().findViewById(R.id.refreshLayout);
//        mDrawerLayout = (DrawerLayout) getView().findViewById(R.id.activity_main_drawerlayout);
//        left_ll = (LinearLayout) getView().findViewById(R.id.activity_main_left_ll);
//        userid = (TextView) getView().findViewById(R.id.activity_main_left_userid);
//        userid.setText(getActivity().getSharedPreferences(ConstantConfigure.SPLOGIN_NAME, getActivity().MODE_PRIVATE).getString("id", "default"));
//        loginout = (TextView) getView().findViewById(R.id.activity_main_left_loginout);
//        loginout.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                AlinkLoginBusiness.getInstance().logout(getActivity(), new IAlinkLoginCallback() {
//                    @Override
//                    public void onSuccess() {
//                        toastActBtm("登出成功");
//                        SystemClock.sleep(500);
//                        getActivity().finish();
//                        ChannelBindHelper.getInstance().onLoginChanged(false);
//
//                    }
//
//                    @Override
//                    public void onFailure(int i, String s) {
//                        toastActBtm("登出失败" + s);
//                    }
//                });
//
//
//            }
//        });
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        adapter = new MyWangGuanAdapter(lists, getActivity());
        adapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        recyclerView.setAdapter(adapter);
//        refreshLayout.setColorSchemeColors(getResources().getColor(R.color.colorTheme), getResources().getColor(R.color.colorTheme), getResources().getColor(R.color.colorTheme));//getResources().getColor(R.color.colorTheme), getResources().getColor(R.color.colorTheme), getResources().getColor(R.color.colorTheme)
        refreshLayout.setOnRefreshListener(this);
        adapter.setListeners(new MyWangGuanAdapter.OnAdapterItemClickListener() {
            @Override
            public void click(WangGuanDeviceEntity bean, int position) {
                Intent intent = new Intent(getActivity(), SubDeviceListActivity.class);
                intent.putExtra("uuid", bean.getUuid());
                intent.putExtra("model", bean.getModel());
                startActivity(intent);
            }
        });
        adapter.setlongListeners(new MyWangGuanAdapter.OnAdapterItemLongClickListener() {
            @Override
            public void click(WangGuanDeviceEntity bean, int position) {
                showPopupWindow(bean);
//                unbind(bean);
            }
        });
    }

    private void init() {
        ArgraceApplication.is_RefreshWangGuanList = true;
        mSVProgressHUD = new SVProgressHUD(getActivity());
        EnvConfigure.init(this.getActivity().getApplicationContext());
        login();
        setView();
    }

    private void login() {
//        if (AlinkLoginBusiness.getInstance().isLogin()) {
//            Toast.makeText(this, "账号已登录", Toast.LENGTH_SHORT).show();
//        } else {
//            openAccountService.showLogin(MainActivity.this, new LoginCallback() {
//                @Override
//                public void onSuccess(OpenAccountSession openAccountSession) {
//                    editor = spLogin.edit();
//                    editor.putString("token", openAccountSession.getAuthorizationCode());
//                    editor.putString("id", openAccountSession.getAuthorizationCode());
//                    editor.putString("otherinfo", openAccountSession.getAuthorizationCode());
//                    editor.putString("mobile", openAccountSession.getUser().mobile);
//                }
//
//                @Override
//                public void onFailure(int i, String s) {
//                    Log.i("info", "登陆失败");
//                }
//            });
//        }
//        if (AlinkLoginBusiness.getInstance().isLogin()) {
//            Log.i("info", "账号已登陆,userid=" + AlinkLoginBusiness.getInstance().getUserID() + "---seeionid" + AlinkLoginBusiness.getInstance().getSessionID() + "--username" + AlinkLoginBusiness.getInstance().getNickName());
//            Toast.makeText(this, "账号已登录", Toast.LENGTH_SHORT).show();
//        } else {
//            Log.i("info", "账号未登录过，跳转到注册界面");
//            AlinkLoginBusiness.getInstance().login(this, null);
//        }
    }


    @Override
    public void onResume() {
        super.onResume();
        if (ArgraceApplication.is_RefreshWangGuanList) {
            onRefresh();
            ArgraceApplication.is_RefreshWangGuanList = false;
        }
    }

    @Override
    public void onRefresh() {
        setRefreshing(true);
        getMyDevice();
    }

    @Override
    public void onLoadMoreRequested() {
        getMyDevice();
    }

    public void setRefreshing(final boolean refreshing) {
        refreshLayout.post(new Runnable() {
            @Override
            public void run() {
                refreshLayout.setRefreshing(refreshing);
            }
        });
    }

    private void getMyDevice() {
        Log.i("info", "MainActivity.getMyDevice()start");
        String method = "mtop.openalink.app.core.devices.getbyuser";
        AlinkHttpUtil.AlinkHttpRequest(method, new HashMap<String, Object>(), new ALinkBusinessEx.IListener() {
            @Override
            public void onSuccess(TransitoryRequest transitoryRequest, TransitoryResponse transitoryResponse) {
                lists.clear();
                setRefreshing(false);
                adapter.loadMoreEnd();
                if (transitoryResponse != null && transitoryResponse.data != null) {
                    Log.i("info", "MainActivity.getMyDevice()--success,data=" + transitoryResponse.data.toString());
                    List<WangGuanDeviceEntity> beans = JSON.parseArray((String) transitoryResponse.data, WangGuanDeviceEntity.class);
                    lists.addAll(beans);
                }
                adapter.notifyDataSetChanged();

            }

            @Override
            public void onFailed(TransitoryRequest transitoryRequest, AError aError) {
                setRefreshing(false);
                adapter.loadMoreEnd();
                Log.i("info", "MainActivity.getMyDevice()--onFailed,code = " + aError.getCode() + ",msg=" + aError.getMsg());
            }
        });
    }

    private void unbind(WangGuanDeviceEntity device) {
        Log.i("info", "MainActivity.unbind()start,uuid = " + device.getUuid());
        String method = "mtop.openalink.app.core.user.unbinddevice";
        HashMap<String, Object> params = new HashMap<>();
        params.put("uuid", device.getUuid());
        AlinkHttpUtil.AlinkHttpRequest(method, params, new ALinkBusinessEx.IListener() {
            @Override
            public void onSuccess(TransitoryRequest transitoryRequest, TransitoryResponse transitoryResponse) {
                Log.i("info", "解绑设备成功,data= " + transitoryResponse.data);
                toastActBtm("解绑成功");
                onRefresh();
            }

            @Override
            public void onFailed(TransitoryRequest transitoryRequest, AError aError) {
                Log.i("info", "解绑设备失败,msg= " + aError.getMsg() + aError.getCode());
                toastActBtm("解绑失败");
            }
        });
    }

    private void loginout() {
        AlinkLoginBusiness.getInstance().logout(getActivity(), new IAlinkLoginCallback() {
            @Override
            public void onSuccess() {
                ChannelBindHelper.getInstance().onLoginChanged(false);

            }

            @Override
            public void onFailure(int i, String s) {

            }
        });

    }

    private void setChouTi() {
        mDrawerLayout.setDrawerListener(new DrawerLayout.DrawerListener() {
            /** 
                      * 当抽屉滑动状态改变的时候被调用 
                      * 状态值是STATE_IDLE（闲置--0）, STATE_DRAGGING（拖拽的--1）, STATE_SETTLING（固定--2）中之一。 
                      * 抽屉打开的时候，点击抽屉，drawer的状态就会变成STATE_DRAGGING，然后变成STATE_IDLE 
                     */
            @Override

            public void onDrawerStateChanged(int arg0) {
                Log.i("drawer", "drawer的状态：" + arg0);
            }

            /** 
                      * 当抽屉被滑动的时候调用此方法 
                      * arg1 表示 滑动的幅度（0-1） 
                      */
            @Override
            public void

            onDrawerSlide(View arg0, float arg1)

            {
                Log.i("drawer", arg1 + "");
            }

            /** 
                      * 当一个抽屉被完全打开的时候被调用 
                      */
            @Override
            public void onDrawerOpened(View arg0)

            {
                Log.i("drawer", "抽屉被完全打开了！");
            }

            /** 
             * 当一个抽屉完全关闭的时候调用此方法 
             */
            @Override
            public void onDrawerClosed(View arg0)

            {
                Log.i("drawer", "抽屉被完全关闭了！");
            }
        });
    }

    private void showPopupWindow(final WangGuanDeviceEntity bean) {
        final AlertDialog alertDialog = new AlertDialog.Builder(
                getActivity()).create();
        alertDialog.setCanceledOnTouchOutside(true);
        alertDialog.show();
        Window window = alertDialog.getWindow();
        window.setContentView(R.layout.dialog_modify);
        RelativeLayout edit = (RelativeLayout) window
                .findViewById(R.id.dialog_modify_rl1);
        edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                alertDialog.dismiss();
                //编辑则弹出修改名字的框
                showModifyNameDialog(bean);
            }
        });

        RelativeLayout del = (RelativeLayout) window
                .findViewById(R.id.dialog_modify_rl2);
        del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                alertDialog.dismiss();
                unbind(bean);
            }
        });
        //加粗
        TextView tx_exit = (TextView) window
                .findViewById(R.id.dialog_modify_text1);
        TextPaint tp1 = tx_exit.getPaint();
        tp1.setFakeBoldText(true);
        TextView tx_logout = (TextView) window
                .findViewById(R.id.dialog_modify_text2);
        TextPaint tp2 = tx_logout.getPaint();
        tp2.setFakeBoldText(true);

    }

    private ArgraceDialog mDialog;

    private void showModifyNameDialog(final WangGuanDeviceEntity bean) {
        if (mDialog == null) {
            mDialog = new ArgraceDialog(getActivity(), 1);
        }
        mDialog.setTitleText("修改设备名字", ArgraceDialog.TITLE_MID)
                .setContextText("", ArgraceDialog.CONTENT_EDIT)
                .setCancelText("取消", true).setConfirmText("发送")
                .setEditHintText("输入新的设备名")
                .setBtnColor(R.color.bg_color, R.color.dialog_orange);
        mDialog.setCancelClickListener(new ArgraceDialog.OnArgraceDialogClickListener() {
            @Override
            public void onClick(ArgraceDialog sweetAlertDialog) {
                sweetAlertDialog.dismiss();
            }
        });
        mDialog.setConfirmClickListener(new ArgraceDialog.OnArgraceDialogClickListener() {
            @Override
            public void onClick(ArgraceDialog sweetAlertDialog) {
                alterDeviceName(String.valueOf(sweetAlertDialog.getEditText()), bean);
                sweetAlertDialog.dismiss();
            }
        });
        mDialog.show();
    }

    private void alterDeviceName(String name, final WangGuanDeviceEntity bean) {
        Logg.i("info", "进行修改设备名" + name);
        mSVProgressHUD.showWithStatus("加载中...");
        String method = "mtop.openalink.app.core.device.update.info";
        HashMap<String, Object> params = new HashMap<>();
        params.put("uuid", bean.getUuid());
        params.put("model", bean.getModel());
        params.put("nickName", name);
        AlinkHttpUtil.AlinkHttpRequest(method, params, new ALinkBusinessEx.IListener() {
            @Override
            public void onSuccess(TransitoryRequest transitoryRequest, TransitoryResponse transitoryResponse) {
                Logg.i("info", "修改设备名成功" + transitoryResponse.data);
                mSVProgressHUD.dismiss();
                onRefresh();
            }

            @Override
            public void onFailed(TransitoryRequest transitoryRequest, AError aError) {
                Logg.i("info", "修改设备名失败" + aError.getMsg() + aError.getCode());
                mSVProgressHUD.dismiss();
                toastActBtm("修改失败，请重试");
            }
        });
    }
}

